//
//  CTMoreViewController.m
//  CT
//
//  Created by liufanwei on 15/4/1.
//  Copyright (c) 2015年 liufanwei. All rights reserved.
//

#import "CTMoreViewController.h"
#import "CommonMicro.h"
#import "UILabel+WBExtension.h"
#import "CTChangePWD.h"
#import "CTNetHelper.h"
#import "CTUserDefaultHelper.h"
#import "BDKNotifyHUD.h"
#import "CTMoreWebViewController.h"
#import "AppDelegate.h"
#import <MessageUI/MessageUI.h>
#import "AFNetworking.h"

@interface CTMoreViewController ()<CTChangePWDDelegate,MFMessageComposeViewControllerDelegate,UIAlertViewDelegate>{
    NSString * url;
    NSString * version;
    NSString *trackViewUrl;
}
@property (weak, nonatomic) IBOutlet UILabel *Version;
@property (weak, nonatomic) IBOutlet UIButton *ButtonExit;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ButtonWidthConstraint;

@end

@implementation CTMoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.barTintColor = kBackGroundColor;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    
    UILabel * title = [UILabel labelWithText: @"更多" font:[UIFont fontWithName:kFontName size:20]];
    title.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = title;
    
    _ButtonExit.clipsToBounds = YES;
    _ButtonExit.layer.cornerRadius = 4;
    _ButtonExit.layer.borderColor = [UIColor grayColor].CGColor;
    _ButtonExit.backgroundColor = [UIColor redColor];
    _ButtonWidthConstraint.constant = self.view.frame.size.width - 32;
    
    version = [self curentVersion];
    _Version.text = version;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    url = Nil;
}

#pragma mark - Table view data source
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    switch (section)
    {
        case 0:
        {
            switch (row)
            {
                case 0:
                    [self sendMSg];
                    break;
                case 1:/// 最新优惠
                    url = @"http://zyt1688.com/zyt/yh.html";
                    break;
                case 2:/// 资费说明
                    url = @"http://zyt1688.com/zyt/zf.html";
                    break;
                case 3:/// 帮助中心
                    url = @"http://zyt1688.com/zyt/bz.html";
                    break;
            }
        }
            break;
        case 1:
        {
            switch (row) {
                case 0:
                    [self chaxun];
                    break;
                case 1:
                    [self showChangePWD];
                    break;
            }
        }
            break;
        case 2:
            [self showCall];
            break;
        case 3:
        {
            switch (row)
            {
                case 0://关于我们
                    url = @"http://zyt1688.com/zyt/gy.html";
                    break;
                case 1:
                    [self checkUpdate];
                    break;
                case 2:
                    url = @"http://wap.zyt1688.com";
                    break;
            }
        }
            break;
    }
    
    if (url ) {
        [self performSegueWithIdentifier:@"gomorewebview" sender:self];
    }
}

-(void)sendMSg{
    if( [MFMessageComposeViewController canSendText] ){
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        controller.messageComposeDelegate = self;
        controller.body = @"分享好友的内容   这是一个神奇的APP，有了它我每个月话费至少节省三分之二，快猛戳链接下载。\rhttp://wap.zyt1688.com/app";
        [self.navigationController presentViewController:controller animated:YES completion:^{
        }];
        [[[[controller viewControllers] lastObject] navigationItem] setTitle:@"测试短信"];//修改短信界面标题
    }else{
        [BDKNotifyHUD notifyHUDWithText:@"设备没有短信功能"];
    }
}

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    [controller dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)showCall{
    NSArray * views = [[NSBundle mainBundle] loadNibNamed:@"CTPopViewIB" owner:self options:Nil];
    UIView * view = [views objectAtIndex:1];
    view.frame = kAppFrame;
    [kAppWindow addSubview:view];
}

-(void)showChangePWD{
    NSArray * views = [[NSBundle mainBundle] loadNibNamed:@"CTPopViewIB" owner:self options:Nil];
    CTChangePWD * view = [views objectAtIndex:0];
    view.delegate = self;
    view.frame = kAppFrame;
    [kAppWindow addSubview:view];
}

-(void)chaxun{
    url = Nil;
    [self performSegueWithIdentifier:@"shengyuedu" sender:self];
}

/*  修改密码
 *  oldpassword 当前密码
 *  newpassword 新密码
 *  account
 */
-(void)onSureClicked:(NSDictionary*)dic{
    NSString * newpwd = [dic objectForKey:@"new"];
    NSString * oldpwd = [dic objectForKey:@"old"];
    NSString * account = [[CTUserDefaultHelper ShareInstance] Account];
    [[CTNetHelper ShareInstance] changePassword:@{@"oldpassword":oldpwd,@"newpassword":newpwd,@"account":account} WithCallBack:^(id data) {
        if ([[data objectForKey:@"code"] integerValue] == 0) {
            [[CTUserDefaultHelper ShareInstance] setPWD:newpwd];
        }
        [BDKNotifyHUD notifyHUDWithText:[data objectForKey:@"msg"]];
    }];
}

-(IBAction)onExitClick:(id)sender{
    [[CTUserDefaultHelper ShareInstance] cleanData];;
    [kAppDelegate ShowLogin];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if (url.length > 0) {
        CTMoreWebViewController * vc = segue.destinationViewController;
        [vc setHidesBottomBarWhenPushed:YES];
        vc.Url = url;
    }
    NSString * name = segue.identifier;
    if([name isEqualToString:@"shengyuedu"]){
        UIViewController * vc = segue.destinationViewController;
        [vc setHidesBottomBarWhenPushed:YES];
    }
}

-(NSString*)curentVersion{
    NSDictionary *infoDictionary =[[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleShortVersionString"];
}

-(void)checkUpdate{
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    [manager GET:@"http://zyt1688.com/zyt/IOSUpdate.txt" parameters:Nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSString *result = [[NSString alloc] initWithData:(NSData*)responseObject encoding:NSUTF8StringEncoding];
//        CGFloat newversion = result.floatValue;
//        CGFloat currentVersion = version.floatValue;
//        if (newversion > currentVersion) {
//            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发现新版本是否更新" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
//            [alert show];
//            [BDKNotifyHUD notifyHUDWithText:@""];
//        }
//        NSLog(@"%@",result);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"ERROR:%@", error);
//    }];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:@"http://itunes.apple.com/lookup?id=990542427" parameters:Nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *infoArray = [responseObject objectForKey:@"results"];
        if (!infoArray || infoArray.count == 0) {
            [BDKNotifyHUD notifyHUDWithText:@"检查更新失败"];
            return ;
        }
        NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
        NSString *latestVersion = [releaseInfo objectForKey:@"version"];
        CGFloat newversion = latestVersion.floatValue;
        CGFloat currentVersion = version.floatValue;
        if (newversion > currentVersion) {
            trackViewUrl = [releaseInfo objectForKey:@"trackViewUrl"];
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发现新版本是否更新" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
            [alert show];
        }else{
            [BDKNotifyHUD notifyHUDWithText:@"你已经是最新版本、无须更新"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%ld",buttonIndex);
    if (buttonIndex == 1) {
        UIApplication *application = [UIApplication sharedApplication];
        [application openURL:[NSURL URLWithString:trackViewUrl]];
    }
}
@end




